﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common;
using System.IO;
using System.Configuration;

namespace RastinArgham.CRM.Web
{
    public partial class company_contact : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();


            if (!securityManager.IsActionPermitted("add_contact") && !securityManager.IsActionPermitted("view_contact"))
                Response.Redirect("~/access_denied.aspx");

            if (!securityManager.IsActionPermitted("add_contact"))
                btnSave.Visible = false;

            if (!Page.IsPostBack)
            {
                LoadCities();
                LoadUsers();

                if (!String.IsNullOrEmpty(Request.QueryString["id"]))
                    LoadContact();
            }
        }

        private void LoadContact()
        {
            int id = -1;
            if (String.IsNullOrEmpty(Request.QueryString["id"]) || !Int32.TryParse(Request.QueryString["id"], out id))
                return;

            Contact c = crmRepository.GetContactById(id);

            Guid currentUserId = securityManager.authProvider.GetCurrentUser().UserId;
            List<Guid> myAccountManagers = crmRepository.FindMyAccountManagers(currentUserId);

            if (!securityManager.IsActionPermitted("all_contacts") && c.AccountOwner != currentUserId && c.AccountManagerId != currentUserId & !myAccountManagers.Contains(c.AccountManagerId))
                Response.Redirect("~/access_denied.aspx");


            CompanyContact cc = c.CompanyContacts.FirstOrDefault();
            txtCompanyName.Text = cc.CompanyName;
            txtManagerFirstName.Text = cc.ManagerFirstName;
            txtManagerLastName.Text = cc.ManagerLastName;
            txtManagerFullname.Text = cc.ManagerFullNameEnglish;
            txtManagerNationalCode.Text = cc.ManagerNationalCode;
            
            if (cc.ManagerBirthday.HasValue)
                txtManagerBirthday.Text = cc.ManagerBirthday.ToJalali();

            txtManagerEducationalMajor.Text = cc.ManagerEducationalMajor;
            txtManagerAcademicalDegree.Text = cc.ManagerAcademicDegree;
            txtCompanyActivityField.Text = cc.CompanyActivityField;

            txtFullContactTitle.Text = c.FullContactTitle;
            txtRegistrationNumber.Text = cc.RegistrationNumber;
            ddlCity.ClearSelection();
            ddlCity.Items.FindByValue(c.CityId.ToString()).Selected = true;
            txtAddress.Text = c.Address;
            txtZipCode.Text = c.ZipCode;
            txtTel.Text = c.Phone;
            txtMobile.Text = c.MobilePhone;
            txtFax.Text = c.Fax;
            txtEmailAddress.Text = c.Email;
            txtWebsite.Text = c.Website;
            ddlUsers.ClearSelection();
            ddlUsers.Items.FindByValue(c.AccountManagerId.ToString()).Selected = true;

            if (!String.IsNullOrEmpty(c.MobinReference))
                txtMobinReference.Text = c.MobinReference;

            if (!String.IsNullOrEmpty(c.Marketer))
                txtMarketer.Text = c.Marketer;

            if (securityManager.IsActionPermitted("change_contact_am"))
                ddlUsers.Enabled = true;
            else
                ddlUsers.Enabled = false;

            if (cc.ServicePhoto != null)
            {
                imgServiceCertificate.Src = "~/GetImage.ashx?ContactId=" + c.ContactId.ToString() + "&Type=CompanyContact_CertificatePhoto&w=50&h=50";
                imgServiceCertificate.Visible = true;
                aServiceCertificate.Attributes.Add("href", "~/show_image.aspx?ContactId=" + c.ContactId.ToString() + "&Type=CompanyContact_CertificatePhoto");
                aServiceCertificate.Visible = true;
            }

            if (cc.IdPhoto != null)
            {
                imgIDPhoto.Src = "~/GetImage.ashx?ContactId=" + c.ContactId.ToString() + "&Type=CompanyContact_ID&w=50&h=50";
                imgIDPhoto.Visible = true;
                aIDPhoto.Attributes.Add("href", "~/show_image.aspx?ContactId=" + c.ContactId.ToString() + "&Type=CompanyContact_ID");
                aIDPhoto.Visible = true;
            }

            if (cc.ChargePhoto != null)
            {
                imgChargePhoto.Src = "~/GetImage.ashx?ContactId=" + c.ContactId.ToString() + "&Type=CompanyContact_ChargePhoto&w=50&h=50";
                imgChargePhoto.Visible = true;
                aChargePhoto.Attributes.Add("href", "~/show_image.aspx?ContactId=" + c.ContactId.ToString() + "&Type=CompanyContact_ChargePhoto");
                aChargePhoto.Visible = true;
            }
        }

        private void LoadUsers()
        {
            ddlUsers.ClearSelection();
            ddlUsers.DataSource = securityManager.GetUsers();
            ddlUsers.DataBind();

            ddlUsers.Items.FindByValue(securityManager.authProvider.GetCurrentUser().UserId.ToString()).Selected = true;

            if (securityManager.IsActionPermitted("change_contact_am"))
                ddlUsers.Enabled = true;
            else
                ddlUsers.Enabled = false;
        }

        private void LoadCities()
        {
            ddlCity.DataSource = crmRepository.GetCitiesByUser(securityManager.authProvider.GetCurrentUser().UserId);
            ddlCity.DataBind();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            
            if (!securityManager.IsActionPermitted("add_contact"))
                Response.Redirect("~/access_denied.aspx");

            if (String.IsNullOrEmpty(Request.QueryString["id"]))
                New();
            else
                Update();
        }

        private void Update()
        {
            int id = -1;
            if (String.IsNullOrEmpty(Request.QueryString["id"]) || !Int32.TryParse(Request.QueryString["id"], out id))
                return;

            Contact c = crmRepository.GetContactById(id);
            c.FullContactTitle = txtFullContactTitle.Text;
            c.Address = txtAddress.Text;
            c.ContactTitle = txtCompanyName.Text;
            c.MobilePhone = txtMobile.Text;
            c.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;
            c.Phone = txtTel.Text;
            c.Email = txtEmailAddress.Text;
            c.Website = txtWebsite.Text;
            c.Fax = txtFax.Text;
            c.ZipCode = txtZipCode.Text;
            c.LastUpdate = DateTime.Now;
            c.AccountManagerId = new Guid(ddlUsers.SelectedValue);

            if (!String.IsNullOrEmpty(txtMobinReference.Text))
                c.MobinReference = txtMobinReference.Text;
            else
                c.MobinReference = String.Empty;

            if (String.IsNullOrEmpty(txtMarketer.Text))
                c.Marketer = String.Empty;
            else
                c.Marketer = txtMarketer.Text;

            CompanyContact cc = c.CompanyContacts.FirstOrDefault();
            cc.CompanyName = txtCompanyName.Text;
            
            cc.ManagerFirstName = txtManagerFirstName.Text;
            cc.ManagerLastName = txtManagerLastName.Text;
            cc.ManagerFullNameEnglish = txtManagerFullname.Text;
            cc.ManagerNationalCode = txtManagerNationalCode.Text;
            cc.ManagerBirthday = txtManagerBirthday.Text.ToDateTime();
            cc.ManagerEducationalMajor = txtManagerEducationalMajor.Text;
            cc.ManagerAcademicDegree = txtManagerAcademicalDegree.Text;
            cc.CompanyActivityField = txtCompanyActivityField.Text;

            cc.RegistrationNumber = txtRegistrationNumber.Text;
            cc.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;
            cc.LastUpdate = DateTime.Now;

            string message = String.Empty;
            long MinSize = Convert.ToInt64(ConfigurationManager.AppSettings["minImageSize"]);
            long MaxSize = Convert.ToInt64(ConfigurationManager.AppSettings["maxImageSize"]);

            Byte[] IdPhotoBytes = UIHelper.CheckAndGetPostedImage(fuIDPhoto, out message, MinSize, MaxSize);
            if (!String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else if ( IdPhotoBytes != null )
            {
                cc.IdPhoto = IdPhotoBytes;
            }

            Byte[] ServicePhotoBytes = UIHelper.CheckAndGetPostedImage(fuServiceCertificatePhoto, out message, MinSize, MaxSize);
            if (!String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else if (ServicePhotoBytes != null)
            {
                cc.ServicePhoto = ServicePhotoBytes;
            }

            Byte[] ChargePhotoBytes = UIHelper.CheckAndGetPostedImage(fuChargeCertificatePhoto, out message, MinSize, MaxSize);
            if (!String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else if (ChargePhotoBytes != null)
            {
                cc.ChargePhoto = ChargePhotoBytes;
            }

            // Checking Dates
            // T-SQL DateTime Valid Range January 1, 1753, through December 31, 9999
            if (!cc.ManagerBirthday.HasValue || !DateTimeHelpers.CheckSqlDate(cc.ManagerBirthday.Value))
            {
                UIHelper.ClientAlert(this, "تاریخ تولد مدیر صحیح نمی باشد لطفا این تاریخ را اصلاح فرمایید");
                return;
            }

            crmRepository.Save();

            UIHelper.ClientAlert(this, "تغییرات با موفقیت ذخیره شد");
            UIHelper.ClientRedirect(this, "dashboard.aspx");
        }

        private void New()
        {
            Contact c = new Contact();
            c.AccountManagerId = new Guid(ddlUsers.SelectedValue);

            if (securityManager.IsUserinRole(securityManager.authProvider.GetCurrentUser().UserName, "mobin"))
            {
                DefaultAccountManager d = crmRepository.GetDefaultAccountManagerForCity(Convert.ToInt32(ddlCity.SelectedValue));
                if ( d != null )
                    c.AccountManagerId = d.UserId;
            }

            c.Address = txtAddress.Text;
            c.City = crmRepository.GetCityByid(Convert.ToInt32(ddlCity.SelectedValue));
            c.ContactTitle = txtCompanyName.Text;
            c.FullContactTitle = txtFullContactTitle.Text;
            c.ContactType = crmRepository.GetContactTypeById((int)ContactTypes.Company);
            c.MobilePhone = txtMobile.Text;
            c.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;
            c.Phone = txtTel.Text;
            c.Email = txtEmailAddress.Text;
            c.Website = txtWebsite.Text;
            c.Fax = txtFax.Text;
            c.ZipCode = txtZipCode.Text;
            c.LeadSourceId = 2;

            if (securityManager.IsActionPermitted("account_owner"))
                c.AccountOwner = securityManager.authProvider.GetCurrentUser().UserId;
            else
                c.AccountOwner = null;

            if (!String.IsNullOrEmpty(txtMobinReference.Text))
                c.MobinReference = txtMobinReference.Text;
            else
                c.MobinReference = String.Empty;

            if (String.IsNullOrEmpty(txtMarketer.Text))
                c.Marketer = String.Empty;
            else
                c.Marketer = txtMarketer.Text;

            CompanyContact cc = new CompanyContact();
            cc.CompanyName = txtCompanyName.Text;
            cc.ManagerFirstName = txtManagerFirstName.Text;
            cc.ManagerLastName = txtManagerLastName.Text;
            cc.ManagerFullNameEnglish = txtManagerFullname.Text;
            cc.ManagerNationalCode = txtManagerNationalCode.Text;
            cc.ManagerBirthday = txtManagerBirthday.Text.ToDateTime();
            cc.ManagerEducationalMajor = txtManagerEducationalMajor.Text;
            cc.ManagerAcademicDegree = txtManagerAcademicalDegree.Text;
            cc.CompanyActivityField = txtCompanyActivityField.Text;
            cc.RegistrationNumber = txtRegistrationNumber.Text;
            cc.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;

            string message = String.Empty;

            long MinSize = Convert.ToInt64(ConfigurationManager.AppSettings["minImageSize"]);
            long MaxSize = Convert.ToInt64(ConfigurationManager.AppSettings["maxImageSize"]);

            Byte[] IdPhotoBytes = UIHelper.CheckAndGetPostedImage(fuIDPhoto, out message, MinSize, MaxSize);
            if (IdPhotoBytes == null && !String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else
            {
                cc.IdPhoto = IdPhotoBytes;
            }

            Byte[] ServicePhotoBytes = UIHelper.CheckAndGetPostedImage(fuServiceCertificatePhoto, out message, MinSize, MaxSize);
            if (ServicePhotoBytes == null && !String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else
            {
                cc.ServicePhoto = ServicePhotoBytes;
            }

            Byte[] ChargePhotoBytes = UIHelper.CheckAndGetPostedImage(fuChargeCertificatePhoto, out message, MinSize, MaxSize);
            if (ChargePhotoBytes == null && !String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else
            {
                cc.ChargePhoto = ChargePhotoBytes;
            }

            // Checking Dates
            // T-SQL DateTime Valid Range January 1, 1753, through December 31, 9999
            if (!cc.ManagerBirthday.HasValue || !DateTimeHelpers.CheckSqlDate(cc.ManagerBirthday.Value))
            {
                UIHelper.ClientAlert(this, "تاریخ تولد مدیر صحیح نمی باشد لطفا این تاریخ را اصلاح فرمایید");
                return;
            }

            crmRepository.AddCompanyContact(c, cc);

            UIHelper.ClientAlert(this, "تغییرات با موفقیت ذخیره شد");
            UIHelper.ClientRedirect(this, "dashboard.aspx");
        }
    }
}